<?php

namespace App\Console\Commands;

use App\Models\BookIsbn;
use App\Services\DoubanService;
use App\Services\GoodService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use function Symfony\Component\VarDumper\Dumper\esc;

class DoubanIsbnCommand extends Command {
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'system:douban';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = '豆瓣isbn数据';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct() {
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function handle() {
		try {
			$this->exec();
		} catch (\Exception $e) {
			dd($e);
		}
	}

	private function exec() {
		$date = Carbon::today()->toDateTimeString();
		$goods = GoodService::isbnGoods();
		$num = 0;
		foreach ($goods as $good) {
			$isbnKey = strlen($good['isbn']) == 13 ? 'isbn13' : 'isbn10';
			$bookIsbn = BookIsbn::where($isbnKey, $good['isbn'])->first();
			if ($bookIsbn) {
				continue;
			}
			print "isbn:" . $good['isbn'] . "\n";
			$num++;
			$data = DoubanService::isbnBook($good['isbn']);
			if (!$data) {
				Log::error("爬取失败", ['num' => $num, 'isbn' => $good['isbn']]);
				print "爬取失败!num:" . $num . 'isbn:' . $good['isbn'];
				return false;
			}
			if (isset($data['code'])) {
				print "跳过:" . $good['isbn'] . "\n";
				continue;
			}
			$rets = GoodService::insertDoubanBook($data);
			if($rets){
                print "成功写入第" . $num . "条\n";
            }else{
			    print "写入失败:".$good['isbn']."\n";
            }

		}
	}
}
